package com.qxzn.app.page;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.util.PermissionUtil;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.page.view.ProgressDialog;
import com.qxzn.app.page.widget.statusbar.StatusBar;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.FixMemLeak;
import com.qxzn.app.util.StatusBarUtil;
import com.qxzn.app.util.SystemUtil;
import com.tbruyelle.rxpermissions2.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;

public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {

    protected Activity mActivity;

    protected LinearLayout llBase;
    protected LinearLayout ll_right_bar;
    protected TextView tv_title;
    protected RelativeLayout rl_title;
    protected LinearLayout title_bar;
    protected LinearLayout ll_left_bar;
    protected ImageView iv_back;
    protected ImageView iv_right;
    protected TextView tv_right;
    protected View view_placeholder;
    private Unbinder unbinder;

    private boolean isVisibility;
    private ProgressDialog progressDialog;
    protected MyDialog dialog;
    protected PermissionUtil util;
    protected boolean needRequestPermission = true;
    protected final String TAG = "BaseActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen();
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏
//        settingStatusBar();
        setContentView(R.layout.activity_base);
        mActivity = this;
        initBaseView();
        unbinder = ButterKnife.bind(this);
        initView();
        EventBusManager.register(this);
        iniTitleBar();
        setStatusBarColor();
        initData(savedInstanceState);
        ActivityStack.addActivity(this);
        Log.e(TAG, "当前启动的Activity名称为: " + getClass().getSimpleName());
    }

    protected void setFullScreen() {

    }

    protected void setStatusBarColor() {
        StatusBar.setStatusBarLightMode(this, Color.WHITE);
    }

    private void initBaseView() {
        llBase = findViewById(R.id.ll_base);
        title_bar = findViewById(R.id.title_bar);
        ll_left_bar = findViewById(R.id.ll_left_bar);
        tv_title = findViewById(R.id.tv_title);
        rl_title = findViewById(R.id.rl_title);
        iv_back = findViewById(R.id.iv_back);
        iv_right = findViewById(R.id.iv_right);
        tv_right = findViewById(R.id.tv_right);
        ll_right_bar = findViewById(R.id.ll_right_bar);

        iv_back.setOnClickListener(this);

//        fixSystemWindows();

        View view = View.inflate(this, initLayout(), null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        llBase.addView(view, layoutParams);
    }

    //设置状态栏样式
    protected void settingStatusBar() {
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_blue));
        StatusBarUtil.setTranslucent(this);
    }

    //填充状态栏
    protected void fixSystemWindows() {
        view_placeholder = findViewById(R.id.view_placeholder);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view_placeholder.getLayoutParams();
        params.height = SystemUtil.getStatusBarHeight(this);
        AppUtil.showLog("params.height：" + params.height);
        view_placeholder.setLayoutParams(params);
    }

    @Override
    protected void onResume() {
        isVisibility = true;
        super.onResume();
//        setStatusBar();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_back) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(EventBusBean busBean) {
        if (busBean.getId() == 8) {
//            setStatusBar();
        }
    }

    //设置加载的布局
    protected abstract int initLayout();

    //初始化控件
    protected abstract void initView();

    //初始化标题栏
    protected abstract void iniTitleBar();

    //初始化数据
    protected abstract void initData(Bundle savedInstanceState);

    //activity跳转
    protected void startActivity(Class<?> page) {
        startActivity(new Intent(this, page));
    }

    public ProgressDialog showProgress() {
        return showProgress(true);
    }

    protected ProgressDialog showProgress(boolean cancelable) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this, cancelable, false);
        }
        if (!progressDialog.isShowing()) {
            if (!this.isFinishing()) {//如果页面没有被关闭则往下执行
                progressDialog.show();
            }
        }
        return progressDialog;
    }

    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            if (!this.isFinishing()) {
                progressDialog.dismiss();
            }
        }
    }

    protected void showPermissionDialog(String message) {
        showPermissionDialog(message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SystemUtil.toPermissionSetting(BaseActivity.this);
                dialog.dismiss();
            }
        });
    }

    protected void showPermissionDialog(String message, final DialogInterface.OnClickListener positiveListener) {
        showDialog("权限请求", message, "下次再说", "去授权", null, positiveListener);
    }

    protected MyDialog.Builder showDialog(String title, String message, final DialogInterface.OnClickListener positiveListener) {
        return showDialog(title, message, null, null, null, positiveListener);
    }

    protected MyDialog.Builder showDialog(String title, String message, String negativeText, String positiveText, final DialogInterface.OnClickListener negativeListener, final DialogInterface.OnClickListener positiveListener) {
        MyDialog.Builder builder = new MyDialog.Builder(this).setTitle(title).setMessage(message).setNegativeButtonText(negativeText).setPositiveButtonText(positiveText)
                .setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (negativeListener != null) {
                            negativeListener.onClick(dialog, which);
                        }
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (positiveListener != null) {
                            positiveListener.onClick(dialog, which);
                        }
                        dialog.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
        return builder;
    }

    /**
     * 动态权限请求
     */
    protected void requestPermission(MyInterface.AllPermissionGrantListener grantListener, Integer... permissionIndex) {
        util = PermissionUtil.getInstant().setActivity(this).requestPermission(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                AppUtil.showLog("BaseActivity.accept");
                if (permission.granted) {
                    if (grantListener != null) {
                        grantListener.onAllPermissionGrant();
                    }
                } else if (permission.shouldShowRequestPermissionRationale) {
                    requestPermission(grantListener, permissionIndex);
                } else {
                    util.showPermissionNeedDialog(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = true;
                            AppUtil.showLog("BaseActivity.setConfirmClick");
                            // 设置你的操作事项
                            CommonUtil.gotoAppDetailIntent(BaseActivity.this);
                            dialog.dismiss();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = false;
                            AppUtil.showLog("BaseActivity.setCancelClick");
                            dialog.dismiss();
                        }
                    }, permissionIndex);
                }
            }
        }, null, permissionIndex);
    }

//    protected void setStatusBar() {
//        if (Build.VERSION.SDK_INT < 16) {
//            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        } else {
//            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
////                    | View.SYSTEM_UI_FLAG_FULLSCREEN //hide statusBar
//                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; //hide navigationBar
//            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
//        }
//    }

    @Override
    protected void onPause() {
        isVisibility = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        EventBusManager.unregister(this);
        if (util != null) {
            util.destroy();
        }
        FixMemLeak.fixLeak(this);
        ActivityStack.removeActivity(this);
    }

}
